/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package project.jpdftools.imagemerger.actionlisteners;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import project.jpdftools.constants.Const.MOVE_ITEM;

/**
 *
 * @author Mido
 */
public class ListUpDownListener implements ActionListener {

    private JList list;
    private DefaultListModel listModel;
    private int move_direction;

    public ListUpDownListener(JList list, DefaultListModel listModel, int move_direction) {
        super();
        this.list = list;
        this.listModel = listModel;
        this.move_direction = move_direction;
    }

    public void actionPerformed(ActionEvent e) {
        //This method can be called only when
        //there's a valid selection,
        //so go ahead and move the list item.
        int moveMe = list.getSelectedIndex();

        // if no component is selected
        if (moveMe < 0) {
            return;
        }

        if (move_direction == MOVE_ITEM.move_up) {
            //UP ARROW BUTTON
            if (moveMe != 0) {
                //not already at top
                swap(moveMe, moveMe - 1);
                list.setSelectedIndex(moveMe - 1);
                list.ensureIndexIsVisible(moveMe - 1);
            }
        } else {
            //DOWN ARROW BUTTON
            if (moveMe != listModel.getSize() - 1) {
                //not already at bottom
                swap(moveMe, moveMe + 1);
                list.setSelectedIndex(moveMe + 1);
                list.ensureIndexIsVisible(moveMe + 1);
            }
        }
    }

    //Swap two elements in the list.
    private void swap(int a, int b) {
        Object aObject = listModel.getElementAt(a);
        Object bObject = listModel.getElementAt(b);
        listModel.set(a, bObject);
        listModel.set(b, aObject);
    }
}
